<?php

namespace app\modules\backend\controllers;

use app\models\AccountTmp;
use app\models\User;
use app\models\UserAssignable;
use app\modules\backend\rbac\models\Assignment;
use Yii;
use app\models\Person;
use app\models\searchs\PersonSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * PersonController implements the CRUD actions for Person model.
 */
class PersonController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Person models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PersonSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Person model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Person model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Person();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Person model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Person model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    public function actionAssign($id){
        $model = $this->findModel($id);
        $var=sprintf("%04d", $model->id);
        $account_tmp = date('ymd'.$var);
        $psw_tmp = $this->generate_password(6);
        $acctmp = AccountTmp::findOne(['person_id'=>$model->id]);
        if($acctmp) {
            $acctmp->account_tmp = $account_tmp;
            $acctmp->psw_tmp = $psw_tmp;
            $acctmp->update();
        }
        else{
            $acctmp = new AccountTmp();
            $acctmp->person_id=$model->id;
            $acctmp->account_tmp = $account_tmp;
            $acctmp->psw_tmp = $psw_tmp;
            $acctmp->save();
        }

        return $this->render('account_assign',['model'=>$model,'acctmp'=>$acctmp,]);
    }

    /**
     * Finds the Person model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Person the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Person::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    public function actionGetroles($id){

        $authManager = \Yii::$app->authManager;
        $selet_user = User::findOne(['person_id'=>$id]);
        $roleObjs = UserAssignable::findAll(['user_id'=>7]);
        $assignedObjs = array();
        if(!$selet_user){

        }else{
            $assignedObjs = $authManager->getRolesByUser($selet_user->id);
        }


        $roles = array();
        foreach($roleObjs as $r){
            $roles[] = $r->role_name;
        }
        $assigned = array();
        foreach($assignedObjs as $a){
            $assigned[] = $a->name;
        }
        $available = array();
        foreach($roles as $role){
            if(in_array($role,$assigned)){
                continue;
            }
            $available[] = $role;
        }
        $roles = [];
        $roles['available'] = $available;
        $roles['assigned'] = $assigned;
        return json_encode($roles);
    }

    public function actionPass($id,$assigned){
        $authManager = \Yii::$app->authManager;
        $assigned = explode(",",$assigned);
        $acctmp = AccountTmp::findOne(['person_id'=>$id]);
        $person = $this->findModel($id);
        if($acctmp){
            $user = User::findOne(['username'=>$acctmp->account_tmp]);
            if($user){
                $user->assign_num = 0;
                $user->person_id = $id;
                $user->setPassword($acctmp->psw_tmp);
                if(!$user->update()){
                    return $this->redirect('index.php?r=/site/error');
                }
            }else{
                $user = new User();
                $user->assign_num = 0;
                $user->username = $acctmp->account_tmp;
                $user->setPassword($acctmp->psw_tmp);
                $user->generateAuthKey();
                $user->person_id=$id;
                $user->email = $person->email;
                if(!$user->save()){
                    return $this->redirect('index.php?r=/site/error');
                }
                $user = User::findOne(['username'=>$acctmp->account_tmp]);
            }
        }else{
            return $this->redirect('index.php?r=/site/error');
        }


        $assigned_orign = array();
        $assignedObjs = $authManager->getRolesByUser($user->id);
        foreach($assignedObjs as $a){
            $assigned_orign[] = $a->name;
        }
        $delete = array();
        foreach($assigned_orign as $a){
            if(in_array($a,$assigned)){
                continue;
            }
            $delete[] = $a;
        }
        $add = array();
        foreach($assigned as $a){
            if(in_array($a,$assigned_orign)){
                continue;
            }
            $add[] = $a;
        }

        Assignment::deleteAll(['item_name'=>$delete,'user_id'=>$user->id]);

        foreach($add as $item=>$name){
            $assignment = new Assignment();
            $assignment->item_name=$name;
            $assignment->user_id=$user->id;
            $assignment->created_at=time();
            var_dump($assignment);
            if(!$assignment->save()){
                var_dump('保存失败');
            }
        }
        $person->is_assigned = 1;


        $person->save();
        $this->successMail($acctmp->account_tmp,$acctmp->psw_tmp,$person->email);
        return $this->redirect('index.php?r=/backend/person');
    }

    public function successMail($username,$password,$address){
        return Yii::$app->mailer->compose()
            //        ->setFrom('zhoujc1104@163.com')
            ->setTo($address)
            ->setSubject('邦伯农业:您的账号已经激活')
            ->setHtmlBody('
                <style>
                    table{
                        marign:0 auto;
                    }
                    table td{
                        width:200px;
                    }
                    table{
                        border: 1px solid #000000;
                    }
                    th{
                        background-color: #CCCCCC;
                    }
                </style>
                <h3>您的账号已经激活请妥善保管好您的密码:</h3>
                <table style="border:1px solid #000;margin:0 auto;">
                    <tr><th>用户名</th><td>'.$username.'</td></tr>
                    <tr><th>密码</th><td>'.$password.'</td></tr>
                </table>')
            ->send();
    }



    function generate_password( $length = 8 ) {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

        $password = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }

        return $password;
    }
}
